import 'dart:io';
import 'package:eshi/app/shi/data/parse/FileParser.dart';
import 'package:eshi/app/shi/widget/desktop_exporter.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart' hide WebResourceError;

import 'web_stub.dart' if (dart.library.html) 'web_iframe_popup.dart';


/// linux下 sudo apt-get install libwebkit2gtk-4.0
class WebTextWidget extends StatefulWidget {
  final String text;
  String url;  // 要加载的网页 URL
  final TextStyle? style;
  final Widget? children;
  WebTextWidget({super.key, this.text="", this.url="", this.children,this.style}){
      url="https://baike.baidu.com/item/$text";
  }
  // 初始化 WebView 平台实现
  static late WebViewController controller;
  
  static initWebView() async{
    
  //   // 确保 Flutter 绑定初始化
    WidgetsFlutterBinding.ensureInitialized();
    if(kIsWeb){
      return;
    }

    if (Platform.isLinux) {
      // 初始化桌面 WebView 窗口设置
      // await WebviewWindow.initialize();
        WidgetsFlutterBinding.ensureInitialized();
    }else{
        controller= WebViewController()
        ..setBackgroundColor(Colors.transparent)
        ..setJavaScriptMode(JavaScriptMode.unrestricted); 
    }
  }
  @override
  _WebTextWidgetState createState() => _WebTextWidgetState();
}

class _WebTextWidgetState extends State<WebTextWidget> {


  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 可点击的文本
        GestureDetector(
          onTap:() {
             showKeyInfo(widget.text,widget.url);
          },
          onLongPress: (){
             var uri = Uri.dataFromString(widget.url);
              // 检查是否能打开该链接
              canLaunchUrl(uri).then((can){
                  if(can){
                    launchUrl(
                      uri,
                      mode: LaunchMode.externalApplication, // 关键：用系统浏览器打开
                    );
                  }
              });
          },
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              if(widget.children!=null)
                widget.children!,
              if(widget.children==null)
                Text(
                  widget.text,
                  style: widget.style?.copyWith(
                    color: Colors.blue,
                    // decoration: TextDecoration.underline,
                  ) ?? const TextStyle(
                    color: Colors.blue,
                    // decoration: TextDecoration.underline,
                  ),
                ),
              // const SizedBox(width: 8),
              // Icon(
              //   _showWebView ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
              //   color: Colors.blue,
              // ),
            ],
          ),
        ),
        
      ],
    );
  }

  showKeyInfo(String text, String uri){
      showDialog(
          context: context,
          builder: (context) => Dialog(
            backgroundColor: Colors.white.withOpacity(0.66), // 调整透明度
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(32.0),
            ),
            child: SizedBox(
              width: MediaQuery.of(context).size.width ,
              height: MediaQuery.of(context).size.height * 0.7,
              child: Column(
                children: [
                  // AppBar(
                  //   title: Text(text),
                  //   automaticallyImplyLeading: false, // 不显示默认返回按钮
                  //   actions: [
                  //     IconButton(
                  //       icon: Icon(Icons.close),
                  //       onPressed: () => Navigator.pop(context),
                  //     ),
                  //   ],
                  // ),
                  Expanded(
                    child: WebView(uri,title:text)
                  ),
                ],
              ),
            ),
          ),
        );
  }
}
class lazyText extends StatefulWidget{
  Future<String> Function() loadText;
  lazyText(this.loadText, {super.key});

  @override
  State<StatefulWidget> createState() => lazyTextState();
}
class lazyTextState extends State<lazyText>{
  String name="";
  @override
  initState(){
    super.initState();
    initName();
  }

  initName() async {
    var data = await widget.loadText();
    setState(() {
      name = data;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Text(name);
  }
}
Widget  WebView(String uri,{String title=""}) {
   if(kIsWeb){
     return  WebIFramePopup(url:uri, title: title, show: true, onClose: () {   });
   }else if (Platform.isLinux) {
      return DesktopExporter(uri,title);
   }else{
      if(uri.startsWith("asset")){
        FileParser.assetsloadString(uri).then((html) => WebTextWidget.controller.loadHtmlString(html) );
      }else{
        WebTextWidget.controller.loadRequest(Uri.parse(uri));
      }
      //  WebTextWidget.controller.loadHtmlString("<body><h1>aaaa</h1></body>");
      return WebViewWidget(controller: WebTextWidget.controller);
   }
}
